package com.wxzl.community.common.base

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.forEach
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.launcher.ARouter
import com.drake.brv.PageRefreshLayout
import com.gyf.immersionbar.ImmersionBar
import com.kongzue.dialogx.dialogs.WaitDialog
import com.wxzl.community.common.R
import com.wxzl.community.common.router.PathConfig
import com.wxzl.community.common.utils.ext.showToast


/***
 * 使用databinding的activity抽像类
 */
abstract class FragmentBase<VM : ViewModelBase, B : ViewDataBinding> : Fragment() {
    val vm by lazy { ViewModelProvider(this).get(vmClass) }
    abstract val layoutId: Int
    abstract val vmClass: Class<VM>

    lateinit var binding: B
    private var lazyLoaded = false
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(layoutId, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding = DataBindingUtil.bind<B>(view)!!
        initView()
        observe()
    }

    open fun initView() {}

    override fun onResume() {
        super.onResume()
        // 实现懒加载
        if (!lazyLoaded) {
            lazyLoadData()
            lazyLoaded = true
        }

    }

    //适用于viewpage加载fragment
    abstract fun lazyLoadData()


    open fun observe() {
        //统一显示错误消息
        vm.api_err.observe(viewLifecycleOwner, {
            requireContext().showToast(it)
            showPageError()
        })
        vm.service_err.observe(viewLifecycleOwner, {
            requireContext().showToast("服务器开小差了")
            showPageError()
        })
        vm.network_err.observe(viewLifecycleOwner, {
            if (it) requireContext().showToast(R.string.network_error)
            showPageError()
        })

        vm.nulldata_err.observe(viewLifecycleOwner, {
            showPageEmpty()
        })

        vm.showProgress.observe(viewLifecycleOwner, Observer {
            if (it) showProgressDialog() else hideProgressDialog()
        })

        vm.err4033.observe(viewLifecycleOwner, {

            ARouter.getInstance().build(PathConfig.login).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()
        })

        vm.token_exception.observe(viewLifecycleOwner, {
            if (it)
                ARouter.getInstance().build(PathConfig.login).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()
        })

    }


    fun showProgressDialog() {

        WaitDialog.show("等待...")
    }

    fun hideProgressDialog() {
        WaitDialog.dismiss()
    }


    /**謤
     * 设置沉浸式状态栏
     * @param colorResId 状态栏颜色
     */

    protected fun initImmersiveStatusBar() {

        ImmersionBar.with(this).statusBarDarkFont(true).fitsSystemWindows(true)
            .statusBarColor(R.color.white).init()

    }


    /**謤
     * 设置沉浸式状态栏
     * @param colorResId 状态栏颜色
     */

    fun initImmersiveStatusBar(color: Int, isDarkFont: Boolean) {

        ImmersionBar.with(this).statusBarDarkFont(isDarkFont).fitsSystemWindows(true)
            .statusBarColor(color).init()

    }

    /**
     * 获取页面中的PageRefreshLayout
     */
    private fun findPageRefreshLayout(): PageRefreshLayout? {
        val rootView = binding.root as? ViewGroup
        rootView?.let {
            if (rootView is PageRefreshLayout) {
                return rootView
            }

            it.forEach { view ->
                if (view is PageRefreshLayout) {
                    return view
                }
            }
        }
        return null
    }

    /**
     * 显示错误页面
     */
    open fun showPageError() {
        val pageLayout = findPageRefreshLayout()
        pageLayout?.showError()
    }

    /**
     * 显示空页面
     */
    open fun showPageEmpty() {
        val pageLayout = findPageRefreshLayout()
        pageLayout?.showEmpty()
    }

}
